# coding:utf-8
from sqlalchemy import Column, String, Integer, DateTime

from database import dbconnect, session_maker, model_list

_, _, DBase = dbconnect()


class CloudEcsInfo(DBase):
    __tablename__ = 'c_ecs_info'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    instance_id = Column(String(255))  # todo:修改线上msyql表定义，之前写错为instace
    department = Column(String(255))
    department_name = Column(String(255))
    resource_group = Column(String(255))
    resource_group_name = Column(String(255))
    instance_name = Column(String(255))
    vpc_id = Column(String(255))
    vswitch_id = Column(String(255))
    ip = Column(String(255))
    eip = Column(String(255))
    cpu = Column(String(255))
    memory = Column(String(255))
    instance_type = Column(String(255))
    os_type = Column(String(255))
    os_name = Column(String(255))
    status = Column(String(255))
    creation_time = Column(String(255))
    record_time = Column(DateTime)


# 返回一个根据部门账号，获取ak，sk的字典
def get_period_ecs_info(start_date, end_date) -> dict:
    """
    获取时间段内，所有ECS的信息，并生成一个字典：
    {
        "<instance-id-001>":{
            "current_cpu_cores" : 2,
            "current_mem_size": 4096,
            "daily_info": {
                "2023-09-21": {'cpu_cores': 2, 'mem_size': 4096},
                "2023-09-20": {'cpu_cores': 2, 'mem_size': 4096}
            }
        },
    }
    :param start_date:
    :param end_date:
    :return:
    """
    ecs_info_dt = {}
    date_li = []
    with session_maker() as session:
        result = session.query(CloudEcsInfo).filter(
            CloudEcsInfo.record_time.between(start_date, end_date)
        ).order_by(CloudEcsInfo.record_time.desc()).all()  # 记录时间倒序，这样首次出现的实例信息，被记为最新信息
        for row in model_list(result):
            date = str(row['record_time']).split(" ")[0]  # 2023-09-15 16:01:33 将删除时间部分
            date_li.append(date)
            tmp_ins_id = row['instance_id']
            tmp_cpu_cores = int(row['cpu'])
            tmp_mem_size = int(row['memory'])

            # 实例ID不存在，则初始化实例信息, 由于是按时间倒序排列，第一次获取的cpu mem信息是最新的
            if tmp_ins_id not in ecs_info_dt.keys():
                ecs_info_dt[tmp_ins_id] = {
                    "current_cpu_cores": tmp_cpu_cores,
                    'current_mem_size': tmp_mem_size,
                    'daily_info': {}
                }
            # 当日数据不存在，则填入当日数据
            if date not in ecs_info_dt[tmp_ins_id]['daily_info'].keys():
                ecs_info_dt[tmp_ins_id]['daily_info'][date] = {
                    'cpu_cores': tmp_cpu_cores,
                    'mem_size': tmp_mem_size
                }
        print("get_ecs_info dates: ", set(date_li))
    return ecs_info_dt
